#!/usr/bin/python
'''
HELLO
Works with AXT alignment lines.
Finds which ests are colinear on a scaffold.
'''
import sys
import os
from operator import itemgetter

# Parameters.
in_file = sys.argv[1]

# Open file.
fin = open(in_file)
lines = fin.readlines()
fin.close()

def process(buffer, est):
	# Skip singeltons
	if len(buffer) == 1:
		print "%i\t%s\t%s" % (4, est, buffer[0][1])
		return
	
	# Check for repeats and strand.
	prev = -1
	strand = buffer[0][9]
	for x in buffer:
		if prev >= int(x[7]):
			print "%i\t%s\t%s" % (3, est, "XX")
			return
			
		if x[9] != strand:
			print "%i\t%s\t%s" % (5, est, "XX")
			return
		prev = int(x[7])

	
	# Check that scaffold coordinates are in order.
	scaf = ""
	pstop = -1
	for x in buffer:
		# ensure we in same scaffold.
		if x[1] != scaf:
			if scaf != "":	
				print "%i\t%s\t%s" % (broke, est, scaf)
			scaf = x[1]
			pstop = -1
			broke = 0
		
		# Check if we in order from pstop.
		if pstop < int(x[4]):
			pstop = int(x[5])
		else:
			broke = 1
	print "%i\t%s\t%s" % (broke, est, scaf)


# Loop over file.
est = ""
buffer = []
for line in lines:
	# Tokenize.
	tmp = line.strip().split()
	
	# Check if done read est.
	if tmp[0] != est:
		# Process.
		if buffer != []:
			# Sort by EST start positions.
			for x in buffer:
				x[7] = int(x[7])
			buffer = sorted(buffer, key=itemgetter(7))
			
			
			#for x in buffer:
			#	print x
			process(buffer, est)
			
		# Reset.
		buffer = []
		est = tmp[0]
		continue
	
	# Add to buffer.
	buffer.append(tmp)
	
	
